package com.itheima.reggie.controller;


import com.itheima.reggie.domain.CustomException;
import com.itheima.reggie.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {Controller.class, RestController.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    //    java.sql.SQLIntegrityConstraintViolationException:
    //    Duplicate entry 'andy' for key 'idx_username'
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //打印日志，输出具体错误信息
        log.error("error{}",ex.getMessage());
        // 根据异常信息，进行具体一异常信息捕获
        //  只有异常信息为Duplicate entry开头的才会被捕获
        if (ex.getMessage().contains("Duplicate entry")){
            //获取错误信息的第二个位置的元素
            String[] split = ex.getMessage().split(" ");
            return R.error(split[2] + "已存在");
        }
        return R.error("未知错误");
    }

    @ExceptionHandler(CustomException.class)
    public R<String>  customExceptionHandler (CustomException ex){
        log.error("error{}",ex);
        return R.error(ex.getMessage());
    }

}
